<?php

/**
 * @deprecated Pouzi triedu Db_DbTable_*
 * 
 * Harmonogram
 *  
 * @author Radovan Dvorsky
 * @version 20100116
 */

require_once 'Zend/Db/Table/Abstract.php';

class Db_Harmonogram extends Zend_Db_Table_Abstract {
	/**
	 * The default table name 
	 */
	protected $_name = 'harmonogram';
	
	/**
	 * Primary key
	 */
	protected $_primary = 'hid';
	
	/**
	 * Parrent tables description 
	 */
	protected $_referenceMap = array(
		'Subject' => array(
			'columns' => array('sid'),
			'refTableClass' => 'Db_Subject',
			'refColumns' => array('sid'),
			'onDelete' => self::CASCADE
		),
		'Commission' => array(
			'columns' => array('cid'),
			'refTableClass' => 'Db_Commission',
			'refColumns' => array('cid')
		),
		'Student' => array(
			'columns' => array('ID_st'),
			'refTableClass' => 'Db_Student',
			'refColumns' => array('ID_st'),
		)
		
	);

	public function getHarmonogramsCount(){
		$select = $this->select();
		$select->from('harmonogram',array('COUNT(hid) as count'));			
		$harmonograms = $this->fetchAll($select);
			
		return $harmonograms->current()->count;
	}
	
	public function orderHarmonograms(){
		
		$adapter = $this->getAdapter();
		$i = 0;
		
		try{
			
			$adapter->beginTransaction();
			$select = $this->select();
			
			$harmonogramsRowset = $this->fetchAll();
			
			$adapter->query('UPDATE harmonogram SET ord=NULL');
			
			foreach($harmonogramsRowset as $harmonogramsRow){
				$this->update(array(
					'ord' => $i
					),
					$adapter->quoteInto('hid = ?',$harmonogramsRow->hid)					
				);				
				$i++;
			}
			
			$cache = Zend_Registry::get('cache');
			$cache->remove('harmonograms');
			
			$adapter->commit();
			
		} catch (Zend_Exception $e){
			$adapter->rollBack();
			throw new Db_Exception($e->getMessage());
		}
	}
	
	public function changePosition($fromPostition,$toPosition){
		try{
			$adapter = $this->getAdapter();
			$adapter->beginTransaction();
			/*
			 * select povodnych hodnot z db
			 */
			$srcRow = $this->find($fromPostition)->current();
			$destRow = $this->find($toPosition)->current();
			
			/*
			 * Nastav hotnotu NULL, kvoli UNIQUE INDEX
			 */
			$this->update(array('ord' => NULL), $adapter->quoteInto('hid = ?',$srcRow->hid));
			
			/*
			 * Nastav nove hodnoty
			 */
			$this->update(array('ord' => $srcRow->ord),$adapter->quoteInto('hid = ?',$destRow->hid));
			$this->update(array('ord' => $destRow->ord),$adapter->quoteInto('hid = ?',$srcRow->hid));			
			
			$cache = Zend_Registry::get('cache');
			$cache->remove('harmonograms');			
			$adapter->commit();
		} catch(Zend_Db_Exception $e){
			$adapter->rollBack();
			throw new Db_Exception($e->getMessage());
		}
		
		
	}
}